import { shallowRef, onUnmounted } from 'vue';
import { hookResult, IS_MODAL } from './bindResult';
import { IModalBinder } from './type';

export interface EditModalProps {
  onSuccess?: (...args: any[]) => void;
}

export function useModalHandler(props: EditModalProps = {}) {
  const { onSuccess } = props;

  const modalRef = shallowRef<IModalBinder | null>();

  const modalValidate = () => {
    if (!modalRef.value) {
      return false;
    }
    if (!modalRef.value[IS_MODAL]) {
      return false;
    }
    return true;
  };

  const initHandler = () => {
    if (modalValidate()) {
      modalRef.value?.registerSuccess(onModalSuccess);
    }
  };

  const unregister = () => {
    if (modalValidate()) {
      modalRef.value?.unregisterSuccess(onModalSuccess);
    }
  };

  function setRef(el: IModalBinder | any) {
    modalRef.value = el;
    if (el === null) {
      return;
    }
    initHandler();
  }

  onUnmounted(() => {
    unregister();
    modalRef.value = null;
  });

  function returnVerifyRef(
    method: (instance: IModalBinder) => Promise<IModalBinder>
  ) {
    if (modalValidate()) {
      return method(modalRef.value as IModalBinder);
    }
    return Promise.reject(new Error('弹窗modalRef为null'));
  }

  function showModal(...params: any[]) {
    return returnVerifyRef((r) => {
      return r.showModal(...params);
    });
  }

  function onModalSuccess(...args: any[]) {
    if (onSuccess) {
      // @ts-ignore
      onSuccess(...args);
    }
  }

  return hookResult(
    {
      showModal,
    },
    {
      ref: setRef,
    }
  );
}
